package org.game.gobang.client.handler;

import io.netty.channel.ChannelHandlerContext;
import javafx.application.Platform;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.game.gobang.client.constant.ClientConstant;
import org.game.gobang.client.support.SuccessBox;
import org.game.model.Click;
import org.game.model.JoinRoom;
import org.game.util.MapUtil;

import java.util.Map;

@Slf4j
public class CustomizeClientHandler extends GobangClientHandler {
    @Override
    protected void allRooms(ChannelHandlerContext ctx, Object value) {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < ClientConstant.rooms.size(); i++) {
                    ClientConstant.rooms.remove(i);
                }

                ((Map) value).forEach((k, v) -> {
                    ClientConstant.rooms.add(k + " | " + ((Double) v).intValue());
                });
            }
        });
    }

    @SneakyThrows
    @Override
    protected void joinRoom(ChannelHandlerContext ctx, Object value) {
        JoinRoom joinRoom = MapUtil.mapToEntity((Map<String, Object>) value, JoinRoom.class);
        ClientConstant.clickedColor = joinRoom.getColor();
        ClientConstant.player = joinRoom.getPlayer();
        ClientConstant.canClick = false;
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                ClientConstant.name.setText(joinRoom.getName());
                ClientConstant.playerLabel.setText(String.valueOf(joinRoom.getPlayer()));
            }
        });
    }

    @Override
    protected void click(ChannelHandlerContext ctx, Object value) {
        Click click = MapUtil.mapToEntity((Map<String, Object>) value, Click.class);
        ClientConstant.canClick = false;
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                System.out.println(click.getPos());
                ClientConstant.gobangButtonList.get(Integer.parseInt(click.getPos())).changeColor(click.getColor());
            }
        });
    }

    @Override
    protected void win(ChannelHandlerContext ctx, Object value) {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                new SuccessBox((String) value);
            }
        });
    }
}
